<template>
  <div class="news-manage-container">
    <el-card class="search-card">
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入标题关键词"
          class="search-input"
          clearable
          @clear="loadNewsList"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="searchCategoryId"
          placeholder="选择分类"
          clearable
          @change="loadNewsList"
        >
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-select
          v-model="searchStatus"
          placeholder="选择状态"
          clearable
          @change="loadNewsList"
        >
          <el-option label="草稿" :value="0"></el-option>
          <el-option label="已发布" :value="1"></el-option>
        </el-select>
        <el-button type="primary" @click="loadNewsList">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button type="success" @click="showAddNewsDialog">
          <el-icon><Plus /></el-icon>新增新闻
        </el-button>
      </div>
    </el-card>

    <!-- 新闻列表 -->
    <el-card v-loading="loading">
      <el-table :data="newsList" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="60"></el-table-column>
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="scope">
            <div class="news-title-cell">
              <el-tag v-if="scope.row.isTop === 1" type="warning" size="small" effect="plain">置顶</el-tag>
              <span class="news-title">{{ scope.row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="120"></el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180"></el-table-column>
        <el-table-column prop="viewCount" label="浏览量" width="90"></el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="viewNews(scope.row.id)">查看</el-button>
            <el-button size="small" type="primary" @click="editNews(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="changeNewsStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '发布' }}
            </el-button>
            <el-button 
              size="small" 
              :type="scope.row.isTop === 1 ? 'info' : 'warning'"
              @click="changeTopStatus(scope.row)"
            >
              {{ scope.row.isTop === 1 ? '取消置顶' : '置顶' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteNews(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新闻编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogType === 'add' ? '新增新闻' : '编辑新闻'" 
      width="70%"
      destroy-on-close
    >
      <el-form :model="newsForm" :rules="rules" ref="newsFormRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="newsForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="newsForm.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <el-input v-model="newsForm.coverImage" placeholder="请输入封面图片URL">
            <template #append>
              <el-button @click="previewImage">预览</el-button>
            </template>
          </el-input>
          <div v-if="newsForm.coverImage" class="image-preview">
            <img :src="newsForm.coverImage" alt="封面预览">
          </div>
        </el-form-item>
        <el-form-item label="分类" prop="categoryIds">
          <el-select 
            v-model="newsForm.categoryIds" 
            multiple 
            placeholder="请选择分类" 
            style="width: 100%"
          >
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="newsForm.status">
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶" prop="isTop">
          <el-switch 
            v-model="newsForm.isTop" 
            :active-value="1" 
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="newsForm.content" 
            :rows="15" 
            placeholder="请输入新闻内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNewsForm" :loading="submitting">
            {{ dialogType === 'add' ? '添加' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览图片 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="50%">
      <div class="image-preview-dialog">
        <img :src="newsForm.coverImage" alt="封面预览">
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import axios from '../../../utils/axios'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表格数据
const newsList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索条件
const searchKeyword = ref('')
const searchCategoryId = ref(null)
const searchStatus = ref(null)

// 分类数据
const categories = ref([])

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const previewVisible = ref(false)
const submitting = ref(false)

// 表单数据
const newsFormRef = ref(null)
const newsForm = reactive({
  id: null,
  title: '',
  content: '',
  author: '',
  coverImage: '',
  status: 1,
  isTop: 0,
  categoryIds: [],
  adminId: null // 会在提交时从会话中获取
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  categoryIds: [
    { type: 'array', required: true, message: '请至少选择一个分类', trigger: 'change' }
  ]
}

// 获取新闻列表
const loadNewsList = async () => {
  loading.value = true
  try {
    const response = await axios.get('/news/admin/list', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchKeyword.value || undefined,
        categoryId: searchCategoryId.value || undefined,
        status: searchStatus.value !== null ? searchStatus.value : undefined
      }
    })
    
    if (response.data.code === 200) {
      newsList.value = response.data.result.records || []
      total.value = response.data.result.total || 0
    } else {
      ElMessage.error(response.data.message || '获取新闻列表失败')
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadNewsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadNewsList()
}

// 获取分类列表
const loadCategories = async () => {
  try {
    const response = await axios.get('/news/category/list')
    if (response.data.code === 200) {
      categories.value = response.data.result || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 显示添加新闻对话框
const showAddNewsDialog = () => {
  dialogType.value = 'add'
  Object.assign(newsForm, {
    id: null,
    title: '',
    content: '',
    author: '',
    coverImage: '',
    status: 1,
    isTop: 0,
    categoryIds: []
  })
  dialogVisible.value = true
}

// 编辑新闻
const editNews = async (row) => {
  dialogType.value = 'edit'
  
  // 先复制行数据到表单
  Object.assign(newsForm, {
    id: row.id,
    title: row.title,
    content: row.content,
    author: row.author,
    coverImage: row.coverImage,
    status: row.status,
    isTop: row.isTop
  })
  
  // 获取新闻的分类ID列表
  try {
    const response = await axios.get('/news/category/ids', {
      params: { newsId: row.id }
    })
    if (response.data.code === 200) {
      newsForm.categoryIds = response.data.result || []
    }
  } catch (error) {
    console.error('获取新闻分类失败:', error)
    ElMessage.error('获取新闻分类失败')
  }
  
  dialogVisible.value = true
}

// 预览图片
const previewImage = () => {
  if (!newsForm.coverImage) {
    ElMessage.warning('请先输入图片URL')
    return
  }
  previewVisible.value = true
}

// 提交新闻表单
const submitNewsForm = async () => {
  if (!newsFormRef.value) return
  
  await newsFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      // 获取管理员ID
      const user = JSON.parse(sessionStorage.getItem('user'))
      if (!user || !user.id) {
        ElMessage.error('未登录或会话失效，请重新登录')
        return
      }
      
      newsForm.adminId = user.id
      
      let response
      if (dialogType.value === 'add') {
        // 添加新闻
        response = await axios.post('/news', newsForm, {
          params: { categoryIds: newsForm.categoryIds }
        })
      } else {
        // 更新新闻
        response = await axios.put('/news', newsForm, {
          params: { categoryIds: newsForm.categoryIds }
        })
      }
      
      if (response.data.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '新闻添加成功' : '新闻更新成功')
        dialogVisible.value = false
        loadNewsList() // 重新加载列表
      } else {
        ElMessage.error(response.data.message || (dialogType.value === 'add' ? '新闻添加失败' : '新闻更新失败'))
      }
    } catch (error) {
      console.error(dialogType.value === 'add' ? '添加新闻失败:' : '更新新闻失败:', error)
      ElMessage.error(dialogType.value === 'add' ? '添加新闻失败' : '更新新闻失败')
    } finally {
      submitting.value = false
    }
  })
}

// 修改新闻状态
const changeNewsStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const confirmMessage = newStatus === 1 ? '确定要发布该新闻吗？' : '确定要下架该新闻吗？'
  
  ElMessageBox.confirm(confirmMessage, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.put('/news/status', null, {
        params: {
          id: row.id,
          status: newStatus
        }
      })
      
      if (response.data.code === 200) {
        ElMessage.success(newStatus === 1 ? '新闻已发布' : '新闻已下架')
        // 更新本地数据
        row.status = newStatus
      } else {
        ElMessage.error(response.data.message || '操作失败')
      }
    } catch (error) {
      console.error('更新新闻状态失败:', error)
      ElMessage.error('更新新闻状态失败')
    }
  }).catch(() => {})
}

// 修改置顶状态
const changeTopStatus = async (row) => {
  const newTopStatus = row.isTop === 1 ? 0 : 1
  const confirmMessage = newTopStatus === 1 ? '确定要将该新闻置顶吗？' : '确定要取消该新闻的置顶吗？'
  
  ElMessageBox.confirm(confirmMessage, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.put('/news/top', null, {
        params: {
          id: row.id,
          isTop: newTopStatus
        }
      })
      
      if (response.data.code === 200) {
        ElMessage.success(newTopStatus === 1 ? '新闻已置顶' : '新闻已取消置顶')
        // 更新本地数据
        row.isTop = newTopStatus
      } else {
        ElMessage.error(response.data.message || '操作失败')
      }
    } catch (error) {
      console.error('更新新闻置顶状态失败:', error)
      ElMessage.error('更新新闻置顶状态失败')
    }
  }).catch(() => {})
}

// 删除新闻
const deleteNews = (id) => {
  ElMessageBox.confirm('确定要删除这篇新闻吗？删除后无法恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.delete(`/news/${id}`)
      if (response.data.code === 200) {
        ElMessage.success('新闻已删除')
        loadNewsList() // 重新加载列表
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除新闻失败:', error)
      ElMessage.error('删除新闻失败')
    }
  }).catch(() => {})
}

// 查看新闻
const viewNews = (id) => {
  router.push(`/news/detail/${id}`)
}

onMounted(() => {
  loadCategories()
  loadNewsList()
})
</script>

<style scoped>
.news-manage-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.news-title-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.news-title {
  display: inline-block;
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-preview {
  margin-top: 10px;
  max-width: 300px;
  max-height: 200px;
  overflow: hidden;
}

.image-preview img {
  width: 100%;
  object-fit: contain;
}

.image-preview-dialog {
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-preview-dialog img {
  max-width: 100%;
  max-height: 500px;
}
</style> 